#include <stdlib.h>
#include <string.h>

#include "macros.h"
#include "simulate.h"
#include "scratchpad.h"

/*
 * This is a first attempt at beating malloc() for allocation of strings
 * during compilation.  It's pretty general, and could probably be done
 * better.
 *
 * Here's what we can assume:
 * Things are going to conform to LIFO order, more or less.
 * Strings will be of the long variety and the short variety.
 * A realloc on strings might be nice, for "a" "b" "c" ... etc
 *
 * Although in rare cases (errors) certain items won't come off until the
 * table is destroyed.
 */
/* Here is what is currently being used:
 *
 * <0> <0> string1 <len1> string2 <len2>
 *                        ^          ^
 *                        last      tail
 *
 * len1 is the length of string1 including the zero at the end
 *
 * Note: "" looks a heck of a lot like a interior freed string.  Currently,
 * we ignore the problem.  In some cases, it could be left dangling, but
 * I don't think that can happen with the present grammar/use of the
 * scratchpad.
 */
/*
 *  Todo: This algorithm might be faster if we aligned to 2 byte
 *  boundaries and used shorts for lengths.  We wouldn't have to
 *  worry about the 256 byte limit then
 */
/*
 * Within this file, a capitalized identifier is that var cast to an
 * unsigned type.  It makes things easier to read than having casts
 * all over the place since we go back and forth a lot.  strict ANSI
 * requires casts from (unsigned char *) to (char *) and back, but
 * we want to deal with strings as unsigned since we keep the length
 * in them.
 */
#define SCRATCHPAD_SIZE  4096

#define SCRATCH_MAGIC ((unsigned char)0xbb)

typedef struct sp_block_s {
	struct sp_block_s *next, *prev;
	char block[2]; /* block[0] must be nonzero, usually SCRATCH_MAGIC */
} sp_block_t;

#define scratch_free_last() \
	scr_tail = --scr_last; \
scr_last -= *scr_tail; \
while (!(*scr_last) && scr_tail != scr_last) { \
	/* check if the one before was already freed */ \
	scr_tail = --scr_last; \
	scr_last -= *scr_tail; \
}

#define Str ((unsigned char *)str)
#define Ptr ((unsigned char *)ptr)
#define Res ((unsigned char *)res)
#define Scratch_large_alloc(x) ((unsigned char *)scratch_large_alloc(x))
#define Strlen(x) (strlen((char *)x))
#define Strcpy(x, y) (strcpy((char *)x, (char *)y))
#define Strncpy(x, y, z) (strncpy((char *)x, (char *)y, z))

/* not strictly ANSI, but should always work ... */
#define HDR_SIZE ((char *)&scratch_head.block[2] - (char *)&scratch_head)
#define FIND_HDR(x) ((sp_block_t *)(x - HDR_SIZE))
#define SIZE_WITH_HDR(x) (x + HDR_SIZE)

static unsigned char scratchblock[SCRATCHPAD_SIZE];
static sp_block_t scratch_head = { 0, 0 };
static unsigned char *scr_last = &scratchblock[2];
static unsigned char *scr_tail = &scratchblock[2];
static unsigned char *scratch_end = scratchblock + SCRATCHPAD_SIZE;

static char *scratch_large_alloc(int size)
{
	sp_block_t *spt;

	spt = (sp_block_t *)malloc(SIZE_WITH_HDR(size));
	if ((spt->next = scratch_head.next))
		spt->next->prev = spt;
	spt->prev = (sp_block_t *)&scratch_head;
	spt->block[0] = SCRATCH_MAGIC;
	scratch_head.next = spt;
	return (char *)&spt->block[2];
}

void scratch_destroy()
{
	sp_block_t *next, *this = scratch_head.next;

	while (this) {
		next = this->next;
		free(this);
		this = next;
	}
	scratch_head.next = 0;
	scr_last = &scratchblock[2];
	scr_tail = &scratchblock[2];
}

char *scratch_copy(char *str)
{
	unsigned char *from, *to, *end;

	/* first, take a wild guess that there is room and save a strlen() :) */
	from = Str;
	to = scr_tail+1;
	end = scratch_end - 2; /* room for zero and len */
	if (end > to + 255) end = to + 255;
	while (*from && to < end)
		*to++ = *from++;
	if (!(*from)) {
		scr_last = scr_tail + 1;
		*to++ = 0;
		scr_tail = to;
		*to = to - scr_last;
		return (char *)scr_last;
	}
	/* ACK! no room. strlen(str) == (from - str) + strlen(from) */
	to = Scratch_large_alloc((from - Str) + Strlen(from) + 1);
	Strcpy(to, str);
	return (char *)to;
}

void scratch_free(char *ptr)
{
	/* how do we know what this is?  first we check if it's the last string
	   we made.  Otherwise, take advantage of the fact that things on the
	   scratchpad have a zero two before them.  Things not on it wont
	   (we make sure of this) */

	if (Ptr == scr_last) {
		scratch_free_last();
	} else if (*(Ptr - 2)) {
		sp_block_t *sbt;

		DEBUG_CHECK(*(Ptr - 2) != SCRATCH_MAGIC, "scratch_free called on non-scratchpad string.\n");
		sbt = FIND_HDR(ptr);
		if (sbt->prev)
			sbt->prev->next = sbt->next;
		if (sbt->next)
			sbt->next->prev = sbt->prev;
		free(sbt);
	} else {
		*ptr = 0; /* mark it as freed */
	}
}

char *scratch_copy_string(char *s) {
	int l;
	register unsigned char *to = scr_tail + 1;
	char *res;

	l = scratch_end - to;

	if (l > 255) l = 255;
	s++;
	while (l--) {
		if (*s == '\\') {
			switch (*++s) {
				case 'n': *to++ = '\n'; break;
				case 't': *to++ = '\t'; break;
				case 'r': *to++ = '\r'; break;
				case 'b': *to++ = '\b'; break;
				case '"':
				case '\\': *to++ = *s; break;
				default:
					   *to++ = *s;
					   yywarn("Unknown \\x char.");
			}
			s++;
		} else if (*s == '"') {
			*to++ = 0;
			if (!l && (to == scratch_end)) {
				res = scratch_large_alloc(to - scr_tail - 1);
				Strcpy(res, scr_tail + 1);
				return res;
			}
			scr_last = scr_tail + 1;
			scr_tail = to;
			*to = to - scr_last;
			return (char *)scr_last;
		} else
			*to++ = *s++;
	}
	/* estimate the length we need */
	/* Note that the last char is we read is ", not \0 - Sym */
	res = scratch_large_alloc(to - scr_tail + strlen(s) - 1);
	Strncpy(res, (scr_tail + 1), (to - scr_tail) - 1);
	to = Res + (to - scr_tail) - 1;
	for (;;) {
		if (*s == '\\') {
			switch (*++s) {
				case 'n': *to++ = '\n'; break;
				case 't': *to++ = '\t'; break;
				case 'r': *to++ = '\r'; break;
				case 'b': *to++ = '\b'; break;
				case '"':
				case '\\': *to++ = *s; break;
				default:
					   *to++ = *s;
					   // TODO: yywarn("Unknown \\x char.");
			}
			s++;
		} else if (*s == '"') {
			*to++ = 0;
			return res;
		} else
			*to++ = *s++;
	}
}

